const router = require('koa-router')();
const routes = require('./route.js');

routes.forEach(row => {
    let res = row.data;
    if (row.fn) {
        router[row.type](row.url, row.fn)
    } else {
        router[row.type](row.url, async(ctx) => {
            //判断有设置pagination参数，设置分页功能
            if (row.pagination && row.pagination.dataKey) {
                let data = dataKey ? [...res[dataKey]] : [];
                let dataKey = row.pagination.dataKey;
                let page = null,
                    size = null,
                    maxPage = 0;
                if (row.type == 'get') {
                    page = (Number(ctx.query.page) || 1) - 1;
                    size = Number(ctx.query.size) || 20;
                    maxPage = data.length / size;
                } else if (row.type == 'post') {
                    page = (Number(ctx.request.body.page) || 1) - 1;
                    size = Number(ctx.request.body.size) || 20;
                    maxPage = Math.ceil(data.length / size);
                }
                res.page = page * 1 + 1;
                res.size = size;
                res.total = data.length;
                if ((page * 1 + 1) > maxPage) {
                    res[dataKey] = [];
                } else {
                    res[dataKey] = data.slice(page * size, page * size + size * 1);
                }
            }
            //延迟响应
            await delayResponse(row.delay || 0)
            ctx.body = res;
        })
    }

})

async function delayResponse(num) {
    return new Promise((resolve) => {
        setTimeout(() => {
            resolve()
        }, num * 1000);
    })
}
module.exports = router;